package com.foreveross.proxyip.application.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.dayatang.domain.InstanceFactory;
import com.foreveross.proxyip.application.ISystemInitApplication;
import com.foreveross.proxyip.core.BaseCode;
import com.foreveross.proxyip.core.pools.ChannelPool;
import com.foreveross.proxyip.core.pools.DbPool;
import com.foreveross.proxyip.core.pools.PoolsManager;
import com.foreveross.proxyip.core.pools.PublicPool;
import com.foreveross.proxyip.core.zk.ZkAppCenter;
import com.foreveross.proxyip.entity.ChannelEntity;
import com.foreveross.proxyip.infra.base.ddd.application.BaseApplicationImpl;
import com.foreveross.proxyip.infra.conf.PropertyUtils;
import com.foreveross.proxyip.infra.conf.system.DefaultPropertiesLoader;

@Service
public class SystemInitApplicationImpl extends BaseApplicationImpl implements
		ISystemInitApplication {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3281042356356812112L;
	
	private static final Logger logger = LoggerFactory.getLogger(SystemInitApplicationImpl.class);

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void init() {

		// 这里应用启动初始化一次，不需要考虑效率，初始化完成就行了。
		PoolsManager poolsManager = InstanceFactory.getInstance(PoolsManager.class);
		boolean isOnlyErpServer = PropertyUtils.getBooleanProperty("proxyip.isOnlyErpServier", DefaultPropertiesLoader.CONFIG_FILE);
		boolean isOnlyDefalutChannel = PropertyUtils.getBooleanProperty("proxyip.isOnlyDefalutChannel", DefaultPropertiesLoader.CONFIG_FILE);

		
		try {
			BaseCode.getInstance().initBaseCode();// 初始化参数
		} catch (Exception e) {
			logger.error("参数初始化错误：", e);
		}
		
		Map context = poolsManager.getChannelPoolMap();
		List<ChannelEntity> list = poolsManager.getChannelEntitys();
		List<String> codes = new ArrayList<String>();
		codes.add(PublicPool.POOL_CODE + "_DoloadTask");
		codes.add(PublicPool.POOL_CODE + "_CheckInTask");
		codes.add(PublicPool.POOL_CODE + "_CheckOutTask");
		codes.add(DbPool.POOL_CODE + "_DoloadTask");
		codes.add(DbPool.POOL_CODE + "_CheckInTask");
		codes.add(DbPool.POOL_CODE + "_CheckOutTask");

		for (ChannelEntity entity : list) {
			codes.add(entity.getCode() + "_CheckInTask");
			codes.add(entity.getCode() + "_CheckOutTask");
		}
		
		String[] codeStrs = new String[codes.size()];
		for (int i = 0; i < codes.size(); i++) {
			codeStrs[i] = codes.get(i);
		} //
		
		try {
			// 注册zookeeper
			ZkAppCenter.getInstance(codeStrs).registerApp();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		DbPool dbPool;
		
		try {
			dbPool = new DbPool();
			// dbPool.open();
			poolsManager.setDbPool(dbPool);

			PublicPool publicPool = new PublicPool();
			poolsManager.setPublicPool(publicPool);
			
			if (!isOnlyErpServer) {
				publicPool.open();
			}

			boolean isOpenPool = Boolean.parseBoolean(BaseCode.getValue("IS_SYSTEM_OPEN_POOL"));
			
			if (!isOpenPool) {
				log.info("不启动ip池。。。");
				return;
			}

			log.info("渠道池等待公共池先加载一会....");
			TimeUnit.SECONDS.sleep(60);
			
			for (ChannelEntity channel : list) {
				boolean isDefault = "default".equals(channel.getCode());
				ChannelPool channelPool = new ChannelPool(publicPool, channel);
				
				if (isDefault) {
					poolsManager.setDefaultChannelPool(channelPool);
				}
				
				context.put(channel.getCode(), channelPool);
				
				if (!isOnlyErpServer) {
					// 是否只开启默认渠道
					if (isOnlyDefalutChannel) {
						if (isDefault) {
							channelPool.open();
							break;
						} 
						
						continue;
					}
					
					channelPool.open();
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void closePoolValidate() {
		PoolsManager poolsManager = InstanceFactory.getInstance(PoolsManager.class);
		poolsManager.getPublicPool().destroy();
		Map<String, ChannelPool> context = poolsManager.getChannelPoolMap();
		
		for (ChannelPool pool : context.values()) {
			pool.destroy();
		}
	}
	
}
